package com.epam.facebook_client.processor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import com.epam.facebook_client.content.contract.AppContract;
import com.epam.facebook_client.manager.HttpClientManager;
import com.epam.facebook_client.parser.FbJsonParser;
import com.epam.facebook_client.wrapper.Photos;
import common.wrapper.JSONObjectWrapper;

public class PhotosProcessor extends AbstractProcessor {

	protected static final String TAG = PhotosProcessor.class.getSimpleName();
	public static final String EXTRA_ALBUM_ID = "extra_album_id";
	public static final String EXTRA_POST_SOURCE = "extra_post_source";
	public static final String EXTRA_POST_MESSAGE = "extra_post_message";
	public static final String EXTRA_RESPONSE = "extra_response";
	public static final String ACTION = "action_photos";
	
	public PhotosProcessor(Context context) {
		super(context);
	}

	@Override
	public Bundle executeGet(Intent intent) throws Exception {
		String url = intent.getStringExtra(EXTRA_URL);
		final String id = intent.getStringExtra(EXTRA_ALBUM_ID);
		
		FbJsonParser parser = new FbJsonParser(getContext());
		List<JSONObjectWrapper> result = parser.parseArray(url);
		
		ContentValues[] values = new ContentValues[result.size()];
		for (int i = 0; i < result.size(); i++) {
			ContentValues value = new ContentValues(1);
			value.put("data", result.get(i).toString());
			value.put("id", id);
			values[i] = value;
		}
		
		getContext().getContentResolver().bulkInsert(getUri(), values);
		
		Photos photos = new Photos(parser.getJson());
		Bundle extras = new Bundle();
		extras.putString(EXTRA_URL, photos.getNext());
		return extras;
	}

	@Override
	public Bundle executeDelete(Intent intent) throws Exception {
		getContext().getContentResolver().delete(getUri(), null, null);
		return executeGet(intent);
	}

	@Override
	public Bundle executePost(Intent intent) throws Exception {
		Bundle extras = intent.getExtras();
		
		String message = extras.getString(EXTRA_POST_MESSAGE);
		String source = extras.getString(EXTRA_POST_SOURCE);
		String url = extras.getString(EXTRA_URL);
		
		Map<String, String> map = new HashMap<String, String>(2);
		map.put(HttpClientManager.POST_PARAM_MESSAGE, message);
		map.put(HttpClientManager.POST_PARAM_SOURCE, source);
		
		String response = HttpClientManager.get(context).postImage(url, map);
		
		Bundle bundle = new Bundle();
		bundle.putString(EXTRA_RESPONSE, response);
		return bundle;
	}

	@Override
	protected Uri getUri() {
		return AppContract.PhotosColumns.CONTENT_URI;
	}

}
